<template>
  <div>
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" label-width="120px" prop="name">
        <el-input v-model="roleForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色描述" label-width="120px">
        <el-input v-model="roleForm.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('success')">取 消</el-button>
      <el-button type="primary" @click="hSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { addRole, updateRole } from '@/api/settings'
export default {
  props: {
    isEdit: {
      type: Boolean
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 侦听 点击 是 编辑 还是 新增
    // 编辑 - 把数据赋值给 roleForm 重新渲染
    // 新增 - 给空值，
    isEdit: {
      handler(newVal) {
        if (newVal) {
          this.roleForm = { ...this.row }
        }
      },
      immediate: true
    }
  },
  methods: {
    // 提交
    hSubmit() {
      this.$refs['roleForm'].validate(async(valid) => {
        if (valid) {
          // 如果 isEdit 为 true 则是点的编辑
          if (this.isEdit) {
            const res = await updateRole(this.roleForm)
            if (res.code === 10000) {
              // 成功后
              this.$emit('success')
              // this.cancel()
            }
          } else {
            const res = await addRole(this.roleForm)
            if (res.code === 10000) {
              // 成功后
              this.$emit('success')
              // this.cancel()
            }
          }
        }
      })
    },
    // 重置
    cancel() {
      this.roleForm = {
        name: '', // 部门
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
